package com.queclink.ycm.container;

import com.queclink.ycm.common.utils.DateUtil;
import com.queclink.ycm.model.NettyClient;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jim.li
 * @email jim.li@queclink.com
 * @date 2022-01-10 09:36:00
 */
public class NettyClients {
    private final static Map<String, NettyClient> nettyClients = new ConcurrentHashMap<>();

    public static void add(String uniqueId, NettyClient nettyClient) {
        nettyClients.put(uniqueId, nettyClient);
    }

    public static void delete(String uniqueId) {
        nettyClients.remove(uniqueId);
    }

    public static NettyClient get(String uniqueId) {
        return nettyClients.get(uniqueId);
    }

    public static NettyClient getByCtx(ChannelHandlerContext channelHandlerContext) {
        NettyClient nettyClient = new NettyClient();
        for (Map.Entry<String, NettyClient> entry : nettyClients.entrySet()) {
            if (entry.getValue().getCtx().equals(channelHandlerContext)) {
                nettyClient.setUniqueId(entry.getValue().getUniqueId());
                nettyClient.setCtx(entry.getValue().getCtx());
                nettyClient.setTime(entry.getValue().getTime());
            }
        }
        return nettyClient;
    }

    public static void remove(ChannelHandlerContext ctx) {
        for (Map.Entry<String, NettyClient> entry : nettyClients.entrySet()) {
            String key = entry.getKey();
            NettyClient nettyClient = entry.getValue();
            if (nettyClient.getCtx() == ctx) {
                System.out.println(DateUtil.getNowFormatDate() + " [" + key + "] Disconnect");
                nettyClients.remove(key);
                break;
            }
        }
    }

    public static Map<String, NettyClient> getNettyClients() {
        return nettyClients;
    }
}
